<?php
class AuthController extends LBController
{
    protected function needAuth()
    {
        return false;
    }

    public function regAction()
    {/*{{{*/
        $this->view->title = gettext('register');
        $page = null;

        if ($this->_request->isPost())
        {
            $userName = filter_var($this->getParam('userName'), FILTER_VALIDATE_EMAIL);
            $password = filter_var($this->getParam('password'));
            $desturl = filter_var($this->getParam('desturl', '/'));

            //create
            $user = new User();
            $res = $user->findByUserName($userName);
            if (null == $res)
            {
                $db = Zend_Db_Table::getDefaultAdapter();
                $db->beginTransaction();
                try
                {
                    $user->createByBiz($userName, $password);
                    $user->save();
                    $profile = new Profile();
                    $profile->createByBiz($user->getUserId(), $user->getUserName());
                    $profile->save();
                    $db->commit();
                    $this->view->user = $user->toArray();
                    $msg = gettext('create user succ!');
                    $page = 'regsucc';
                }
                catch (Zend_Db_Statement_Exception $e)
                {
                    $db->rollBack();
                    $logger = Logger::getExceptionLogger();
                    $logger->err($e->getMessage() . "\n" .  $e->getTraceAsString());
                    $msg = gettext('create user error!');
                }
            }
            else
            {
                $msg = gettext('user is exist!');
            }
            $this->view->msg = $msg;
        }

        $this->render($page);
    }/*}}}*/

    public function loginAction()
    {/*{{{*/
        $this->view->message = '';
        if ($this->_request->isPost())
        {
            $userName = filter_var($this->getParam('userName'), FILTER_VALIDATE_EMAIL);
            $password = filter_var($this->getParam('password'));
            $desturl = filter_var($this->getParam('desturl', '/'));

            try
            {
                $user = new User();
                $userRes = $user->authorize($userName, $password);
                $arr = $userRes->toArray();
                $userId = $arr['userId'];

                $profile = new Profile();
                $infoRes = $profile->findByUserId($userId);
                $info = $infoRes->toArray();
                $info = array_merge($info, array('crumb'=>User::genAuthCrumb($userName)));

                $sess = $this->getSessSvc();
                $sess->save('info', $info);
                $this->redirect($desturl);

            }
            catch (UserException $e)
            {
                $this->view->msg = $e->getMessage();
                $this->render();
            }
        }
    }/*}}}*/

}
